﻿using Newtonsoft.Json.Linq;
using System;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Change.uc
{
    public partial class ucBlueprint : UserControl
    {
        SQLiteConnection conn;
        //定义委托
        delegate void inittvItemsDelegate();
        delegate void AsynUpdateUI1(string step);   //更新UI1
        delegate void AsynUpdateUI2(TreeNode root);//更新UI2

        public delegate void UpdateUI(string step);//声明一个更新主线程的委托
        public UpdateUI UpdateUIDelegate;

        public delegate void AccomplishTask(TreeNode root);//声明一个在完成任务时通知主线程的委托
        public AccomplishTask TaskCallBack;

        string yearID;

        public ucBlueprint()
        {
            InitializeComponent();

            tvBluePrint.Nodes.Add("正在连接数据库");
            yearID = getYearID();

            UpdateUIDelegate += UpdataUIStatus;//绑定更新任务状态的委托
            TaskCallBack += Accomplish;//绑定完成任务要调用的委托
            //启动线程
            Thread thread = new Thread(initBlueprint);
            thread.IsBackground = true;
            thread.Start();
        }
        //更新UI
        private void UpdataUIStatus(string step)
        {
            if (InvokeRequired)
            {
                this.Invoke(new AsynUpdateUI1(delegate (string s)
                {
                    //this.pgbWrite.Value += s;
                    //this.lblWriteStatus.Text = this.pgbWrite.Value.ToString() + "/" + this.pgbWrite.Maximum.ToString();
                    tvBluePrint.Nodes.Add(s);
                }), step);
            }
        }

        //完成任务时需要调用
        private void Accomplish(TreeNode root)
        {
            if (InvokeRequired)
            {
                this.Invoke(new AsynUpdateUI2(delegate (TreeNode rt)
                {
                    //this.pgbWrite.Value += s;
                    //this.lblWriteStatus.Text = this.pgbWrite.Value.ToString() + "/" + this.pgbWrite.Maximum.ToString();
                    tvBluePrint.Nodes.Clear();
                    tvBluePrint.Nodes.Add(rt);
                }), root);
            }
        }
        private string getYearID()
        {
            FileStream fs = new FileStream("db/eve.cfg", FileMode.Open, FileAccess.Read);

            StreamReader sr = new StreamReader(fs);

            string yearid = sr.ReadToEnd();

            return yearid;
        }

        private void initBlueprint()
        {
            TreeNode root = new TreeNode();


            root.Tag = 0;
            root.Text = "蓝图和反应物-" + yearID;
            root.Expand();
            try
            {
                conn = new SQLiteConnection("Data Source=db/eve.db;Version=3;");
                conn.Open();

                UpdateUIDelegate("数据库已连接，正在加载数据...");
            }
            catch (Exception ex)
            {
                throw ex;
            }


            setTreeView(root, 0);
            UpdateUIDelegate("正在加载蓝图类别数据");
            setTreeViewLeaf(root);
            UpdateUIDelegate("蓝图数据加载完毕.");
            TaskCallBack(root);
        }

        private void setTreeView(TreeNode tr1, int parentId)
        {
            string sql;
            if (parentId == 0)
                sql = "select marketGroupID,marketGroupName_zh,parentGroupID from invmarketgroups where parentGroupID =2";
            else
                sql = "select marketGroupID,marketGroupName_zh,parentGroupID from invmarketgroups where parentGroupID=" + parentId;
            SQLiteDataAdapter reader = new SQLiteDataAdapter(sql, conn);

            DataTable dt = new DataTable();
            reader.Fill(dt);

            if (dt.Rows.Count > 0)
            {

                int pId = -1;
                foreach (DataRow row in dt.Rows)
                {
                    TreeNode node = new TreeNode();
                    node.Text = row[1].ToString();
                    node.Tag = Convert.ToInt32(row[0]);
                    if (row[2] is System.DBNull)
                        pId = 0;
                    else
                        pId = Convert.ToInt32(row[2]);
                    if (pId == 2)
                    {
                        //添加根节点
                        tr1.Nodes.Add(node);
                    }
                    else
                    {
                        //添加根节点之外的其他节点
                        RefreshChildNode(tr1, node, pId);
                    }
                    //查找以node为父节点的子节点
                    setTreeView(tr1, Convert.ToInt32(node.Tag));

                }
            }

        }
        /// <summary>
        /// 查找叶子节点
        /// </summary>
        /// <param name="tr1"></param>
        private void setTreeViewLeaf(TreeNode tr1)
        {

            foreach (TreeNode node in tr1.Nodes)
            {
                //查找树的叶子节点
                if (node.Nodes.Count == 0)
                {
                    addNodeLeaf(node);

                }
                else
                {
                    findTreeViewLeaf(node);
                }
                UpdateUIDelegate("加载蓝图--" + node.Text);
            }
        }
        /// <summary>
        /// 第二层遍历，加速函数
        /// </summary>
        /// <param name="tr1"></param>
        private void findTreeViewLeaf(TreeNode tr1)
        {
            foreach (TreeNode node in tr1.Nodes)
            {
                //查找树的叶子节点
                if (node.Nodes.Count == 0)
                {
                    addNodeLeaf(node);

                }
                else
                {
                    flashTreeViewLeaf(node);
                }

            }
        }
        /// <summary>
        /// 第三层遍历，加速函数
        /// </summary>
        /// <param name="node"></param>
        private void flashTreeViewLeaf(TreeNode tr1)
        {
            foreach (TreeNode node in tr1.Nodes)
            {
                //查找树的叶子节点
                if (node.Nodes.Count == 0)
                {
                    addNodeLeaf(node);

                }
                else
                {
                    flashTreeViewLeaf(node);
                }

            }
        }


        /// <summary>
        /// 添加叶子节点
        /// </summary>
        /// <param name="node"></param>
        private void addNodeLeaf(TreeNode node)
        {
            int pid = Convert.ToInt32(node.Tag);

            string sql = "select typeID,typeName_zh from invtypes where marketGroupID=" + pid;

            SQLiteDataAdapter reader = new SQLiteDataAdapter(sql, conn);

            DataTable dtLeaf = new DataTable();

            reader.Fill(dtLeaf);
            if (dtLeaf.Rows.Count > 0)
            {
                foreach (DataRow dr in dtLeaf.Rows)
                {
                    TreeNode nodeleaf = new TreeNode();
                    nodeleaf.Text = dr[1].ToString();
                    nodeleaf.Tag = Convert.ToInt32(dr[0]);

                    node.Nodes.Add(nodeleaf);
                }
            }
        }
        //处理根节点的子节点
        private void RefreshChildNode(TreeNode tr1, TreeNode treeNode, int parentId)
        {
            foreach (TreeNode node in tr1.Nodes)
            {
                if (Convert.ToInt32(node.Tag) == parentId)
                {
                    node.Nodes.Add(treeNode);
                    return;
                }
                else if (node.Nodes.Count > 0)
                {
                    FindChildNode(node, treeNode, parentId);
                }
            }
        }

        //处理根节点的子节点的子节点
        private void FindChildNode(TreeNode tNode, TreeNode treeNode, int parentId)
        {
            foreach (TreeNode node in tNode.Nodes)
            {
                if (Convert.ToInt32(node.Tag) == parentId)
                {
                    node.Nodes.Add(treeNode);
                    return;
                }
                else if (node.Nodes.Count > 0)
                {
                    FindChildNode(node, treeNode, parentId);
                }

            }

        }

        private void tvBluePrint_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {

            if (e.Node.Nodes.Count > 0)
                return;
            int typeID = Convert.ToInt32(e.Node.Tag);
            string strname = e.Node.Text;
            labName.Text = strname;

            string sql = "select maxProductionLimit from industryBlueprints where blueprintTypeID=" + typeID;

            SQLiteDataAdapter reader = new SQLiteDataAdapter(sql, conn);

            DataTable dt = new DataTable();

            reader.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                tbmax.Text = dt.Rows[0][0].ToString();
            }

            sql = "select activityID,time from industryActivities where blueprintTypeID=" + typeID;

            reader = new SQLiteDataAdapter(sql, conn);

            dt = new DataTable();

            reader.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    string stime = ConvertTime(dr[1].ToString());
                    switch(dr[0].ToString())
                    {
                        case "1":
                            labmanufacturing.Text = stime;
                            break;
                        case "3":
                            labresearch_material.Text = stime;
                            break;
                        case "4":
                            labresearch_time.Text = stime;
                            break;
                        case "5":
                            labCopytime.Text = stime;
                            break;
                        case "8":
                            labinvention.Text = stime;
                            break;
                        default:
                            break;
                    }
                }
            }
            //制造时间
            sql = "select activityID,productTypeID,quantity,probability from industryActivityProducts where blueprintTypeID=" + typeID;

            reader = new SQLiteDataAdapter(sql, conn);

            dt = new DataTable();

            reader.Fill(dt);

            tbInv.Text = "";
            tbInvNum.Text = "";
            tbInvRate.Text = "";
            cmbProduct.Items.Clear();
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    switch (dr[0].ToString())
                    {
                        case "1":
                            tbProduct.Text    = GetProductName(dr[1].ToString());
                            tbProductNum.Text = dr[2].ToString();
                            break;
  
                        case "8":
                            tbInv.Text=GetProductName(dr[1].ToString());
                            tbInvNum.Text = dr[2].ToString();
                            tbInvRate.Text = ConvertRate(dr[3].ToString());
                            cmbProduct.Items.Add(tbInv.Text);
                            
                            break;
                        default:
                            break;
                    }
                }
            }
            //材料计算
            sql = "select activityID,materialTypeID,quantity from industryActivityMaterials where blueprintTypeID=" + typeID;

            reader = new SQLiteDataAdapter(sql, conn);

            dt = new DataTable();
            dt.Rows.Clear();
            reader.Fill(dt);
            dwMaterials.Rows.Clear();
            dwInvMaterials.Rows.Clear();
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    switch (dr[0].ToString())
                    {
                        case "1":                    

                            int index = this.dwMaterials.Rows.Add();
                            //dwMaterials.Rows[index].Cells[0].Value = 1 + index;
                            dwMaterials.Rows[index].Cells[0].Value = GetGroupName(dr[1].ToString());
                            dwMaterials.Rows[index].Cells[1].Value = GetProductName(dr[1].ToString());//名称
                            dwMaterials.Rows[index].Cells[4].Value = dr[2].ToString(); //数量
                            dwMaterials.Rows[index].Cells[5].Value = GetPrice(dr[1].ToString(),0);//价格
                            

                            break;


                        case "8":
                            index = this.dwInvMaterials.Rows.Add();
                            dwInvMaterials.Rows[index].Cells[0].Value = GetGroupName(dr[1].ToString());
                            dwInvMaterials.Rows[index].Cells[1].Value = GetProductName(dr[1].ToString());//名称
                            dwInvMaterials.Rows[index].Cells[2].Value = dr[2].ToString(); //数量
                            dwInvMaterials.Rows[index].Cells[3].Value = GetPrice(dr[1].ToString(),0);//价格
                            break;
                        default:
                            break;
                    }
                }
            }
        }

        private string GetPrice(string v,int flag)
        {
            string retprice="";
            string retString = "";
            string buyitem, sellitem;
            int typeID= Convert.ToInt32(v.ToString());
            string url = "http://www.ceve-market.org/api/market/region/10000002/system/30000142/type/" + typeID + ".json";   //国服市场中心API的URL
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Proxy = null;
                request.KeepAlive = false;
                request.Method = "GET";
                request.ContentType = "application/json; charset=UTF-8";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream rs = response.GetResponseStream();
                StreamReader sr = new StreamReader(rs, Encoding.UTF8);
                retString = sr.ReadToEnd();
                rs.Close();
                sr.Close();
            }
            catch (WebException ex)
            {
                MessageBox.Show("错误：" + ex);
                throw ex;
            }


            JObject price = JObject.Parse(retString);
            JObject sell = (JObject)price["sell"];
            JObject buy = (JObject)price["buy"];
            string sel = (string)sell["min"];
            string bu = (string)buy["max"]; //JSON转化
            //long lsell = (long)sell["volume"];
            //DateTime dtsell = new DateTime(lsell);
            //long lbuy = (long)buy["volume"];
            //DateTime dtbuy= new DateTime(lbuy);

            if (sel == null)
            {
                sellitem = " ";
            }
            else
            {

                sellitem = string.Format("{0:0,0.00}", float.Parse(sel));
            }
            if (bu == null)
            {
                buyitem = " ";
            }
            else
            {
                buyitem = string.Format("{0:0,0.00}", float.Parse(bu));
            }
            if (flag == 0)
                retprice = sellitem;
            else if(flag == 1)
                retprice = buyitem;
             return retprice;
        }

        private string GetGroupName(string nv)
        {
            string name = "";
            int typeID = Convert.ToInt32(nv);
            string gid = "";

            string sql = "select groupID from invtypes where typeID = " + typeID;

            SQLiteDataAdapter reader = new SQLiteDataAdapter(sql, conn);

            DataTable dt = new DataTable();

            reader.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                gid = dt.Rows[0][0].ToString();
                name = getGroupName2(gid);
            }

            return name;
        }

        private string getGroupName2(string gid)
        {
            string name = "";
            int typeID = Convert.ToInt32(gid);
            

            string sql = "select name_zh from invgroups where groupID = " + typeID;

            SQLiteDataAdapter reader = new SQLiteDataAdapter(sql, conn);

            DataTable dt = new DataTable();

            reader.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                name = dt.Rows[0][0].ToString();
                 
            }

            return name;
        }

        //转为百分数
        private string ConvertRate(string rv)
        {
           int dv=Convert.ToInt32(Convert.ToDouble(rv)*100); 
            
           string cv=dv.ToString()+"%";
            return cv;    
        }

        private string GetProductName(string nv)
        {
            string name="";
            int typeID = Convert.ToInt32(nv);

            string sql= "select typeName_zh from invtypes where typeID = " + typeID;

            SQLiteDataAdapter reader = new SQLiteDataAdapter(sql, conn);

            DataTable dt = new DataTable();

            reader.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                name = dt.Rows[0][0].ToString();
            }

            return name;
        }

        private string ConvertTime(string cv)
        {
            int secondv=Convert.ToInt32(cv);
            int s = (secondv % 3600)%60;
            int m= (secondv % 3600)/60;
            int h= (secondv % (3600 * 24)) / 3600;
            int d=  secondv /(3600*24);

            string rs="";

            if (d > 0)
                rs = d.ToString() + "天";
            if (h > 0)
                rs = rs+h.ToString() + "小时";
            if (m > 0)
                rs = rs + m.ToString() + "分";
            if (s > 0)
                rs = rs + s.ToString() + "秒";
            return rs;


        }

        private void cmbProduct_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
